//index.js
//获取应用实例
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');

Page({
  data: {
    win_height: 0,
    nickName: "",
    avatarUrl: "",
    longitude: 0,
    latitude: 0,
    markers: [],
    controls: [],
    shopList: [], //店铺列表 
    navigatorHidden: true,
    shopImage: '',
    shopName: '',
    shopId: '',
    topHeight: 0
  },

  onLoad: function () {
    wx.showLoading({
      title: '加载中',
    })
    this.adjustMap();
    this.adjustLocation();
    this.authorization();
  },
  //获取店铺列表
  getMarker: function () {
    var that = this;
    api.POST({
      params: { page: 1, limit: 100 },
      url: app.globalData.shopList_url,
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          
          var shop = res.data.data.shop_list;
          if (shop.length > 0) {
            var markers = [], shopList = [];
            for (let i in shop) {
              var marker = {
                id: i,
                latitude: shop[i].add_info.location_latitude,
                longitude: shop[i].add_info.location_longitude,
                iconPath: '../../images/ic_point.png',
                width: 21,
                height: 32
              }
              markers.push(marker)
              var new_shop = shop[i];
              new_shop.shopImage = ((new_shop.shopImage == '' || new_shop.shopImage == undefined) ? '../../images/ic_shop_default.png' : new_shop.shopImage);
              shopList.push(new_shop)
            }
            that.setData({
              shopList: shop,
              markers: markers
            })
          }
        } else {

        }
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("网络错误");
      }
    })
  },

  //地图
  adjustMap: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          win_height: res.windowHeight,
          // controls: [{
          //   id: 1,
          //   iconPath: '../../images/ic_location.png',
          //   position: {
          //     left: 16,
          //     top: res.windowHeight - that.data.topHeight,
          //     width: 64,
          //     height: 64
          //   },
          //   clickable: true
          // }, {
          //   id: 2,
          //   iconPath: '../../images/ic_shaoyishao.png',
          //   position: {
          //     left: (res.windowWidth - 64) / 2,
          //     top: res.windowHeight - that.data.topHeight-120,
          //     width: 64,
          //     height: 102
          //   },
          //   clickable: true
          // }],
        })
      }
    })
  },
  //定位
  adjustLocation: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
      fail: function (fail_res) {
        if (fail_res.errMsg == "getLocation:fail 用户拒绝授权"){
          that.showModal();
        } else {
          util.showError("定位失败");
        }
      }
    })
  },
  // 登录
  authorization: function () {
    var that = this
    wx.login({
      success: function (res_login) {
        wx.getUserInfo({
          withCredentials: true,
          success: function (res_user) {
            var login_code = res_login.code;
            var login_encryptedData = res_user.encryptedData;
            var login_iv = res_user.iv;
            that.autoLogin(login_code, login_encryptedData, login_iv);
            that.setData({
              avatarUrl: res_user.userInfo.avatarUrl,
              nickName: res_user.userInfo.nickName,
            });
          }, fail: function (fail_res) {
            if (fail_res.errMsg == "getUserInfo:fail auth deny") {
              that.showModal();
            }else{
              util.showError("登录失败");
            }
          }
        })
      }, fail: function (fail_login) {
        //console.log("fail");
      }
    })
  },

  autoLogin: function (login_code, login_encryptedData, login_iv) {
    var that = this
    var params = {
      code: login_code,
      encryptedData: login_encryptedData,
      iv: login_iv
    }
    api.POST({
      params: params,
      url: app.globalData.login_url,
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          app.globalData.accountInfo = res.data.data.result;
        }
        that.getMarker();
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  // 重新授权
  reAuthorization: function () {
    var that = this
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"] && res.authSetting["scope.userLocation"]) {
          //检测是否有登录信息
          if (that.data.nickName == "" && that.data.avatarUrl == "") {
            that.authorization();
          }
          //检测是否有定位信息
          if (that.data.longitude == 0 && that.data.latitude == 0) {
            that.adjustLocation();
          }
        } else {
          that.showModal();
        }
      }
    })
  },

  showModal: function () {
    var that = this;
    wx.showModal({
      title: '警告',
      content: '若不授权，则无法使用',
      confirmText: '授权',
      cancelText: '不授权',
      success: function (suress) {
        if (suress.confirm) {
          that.reAuthorization();
        } else {
          that.showModal();
        }
      }
    })
  },



  //点击标记点触发
  markerTap: function (e) {
    var that = this;
    var markerId = e.markerId;
    // console.log(e);
    var shop = that.data.shopList[markerId]
    that.setData({
      navigatorHidden: false,
      shopName: shop.shop_name,
      shopImage: shop.shopImage,
      shopId: shop.id,
      topHeight:60
    })
    this.adjustMap();
  },

  //点击控件触发
  mapControlClick: function (e) {
    if (e.controlId == "1") {
      this.adjustLocation();
    } else if (e.controlId == "2") {
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          var scanCode = res.result;
          // wx.navigateTo({
          //   url: '../orderCode/orderCode?oid=4463094' ,
          // })
          if (scanCode.lastIndexOf("type=px") >= 0) {
            var shopId = scanCode.substring(scanCode.lastIndexOf("=") + 1);
            wx.navigateTo({
              url: '../classification/classification?index=2&shopId=' + shopId,
            })
          } else if (scanCode.lastIndexOf("type=oid") >= 0){
            var oid = scanCode.substring(scanCode.lastIndexOf("=") + 1);
            wx.navigateTo({
              url: '../orderCode/orderCode?oid=' + oid,
            })
          } else {
            wx.navigateTo({
              url: '../pickup/pickup'
            })
          }
        },
        fail: function (e) {
          if (e.errMsg != 'scanCode:fail cancel') {
            util.showError("扫码失败");
          }
        }
      });
    }
  },

})
